<?php
/**
 * 菜单帮助类
 * 用于admin模块的菜单相关通用方法
 */
namespace app\module\admin\common;

use think\facade\Db;
use think\facade\Session;
use think\wenhainan\Auth;

class MenuHelper
{
    /**
     * 根据用户权限过滤菜单
     * @param array $menus 菜单数组
     * @param array $authList 用户权限列表
     * @return array 过滤后的菜单
     */
    public static function filterMenusByAuth($menus, $authList)
    {
        // 如果不是数组或者为空，直接返回
        if (!is_array($menus)) {
            return $menus;
        }
        
        foreach ($menus as $key => &$menu) {
            // 检查是否有权限
            $menuKey = $menu['key'] ?? '';
            
            // 如果有key且key在权限列表中，设置为显示
            if (!empty($menuKey) && in_array($menuKey, $authList)) {
                $menu['is_show'] = true;
                // 如果父节点不需要隐藏，继续检查子节点的权限
                if (isset($menu['children']) && is_array($menu['children'])) {
                    $menu['children'] = self::filterMenusByAuth($menu['children'], $authList);
                }
            } else {
                $menu['is_show'] = $menu['is_show'] ?? false;
                // 如果有子节点，继续检查
                if (isset($menu['children']) && is_array($menu['children'])) {
                    $menu['children'] = self::filterMenusByAuth($menu['children'], $authList);
                }
            }
        }
        
        // 移除引用
        unset($menu);
        
        return $menus;
    }

    /**
     * 获取权限列表
     * @param $uid
     * @param $type
     * @return array|mixed
     */
    public static function getAuthList($uid, $type = 1)
    {
        $auth = Auth::instance();
        static $_authList = []; //保存用户验证通过的权限列表
        $t = implode(',', (array)$type);
        if (isset($_authList[$uid . $t])) {
            return $_authList[$uid . $t];
        }
        if (2 == config('auth.auth_type') && Session::has('_auth_list_' . $uid . $t)) {
            return Session::get('_auth_list_' . $uid . $t);
        }
        //读取用户所属用户组
        $groups = $auth->getGroups($uid);
        $ids = []; //保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);
        if (empty($ids)) {
            $_authList[$uid . $t] = [];
            return [];
        }
        $map = [
            ['type','=',$type],
            ['id','in', $ids],
            //['status','=',1],
        ];
        //读取用户组所有权限规则
        $rules = Db::name(config('auth.auth_rule'))->where($map)->field('condition,name')->select();
        //循环规则，判断结果。
        $authList = []; //
        $condition = '';
        foreach ($rules as $rule) {
            if (!empty($rule['condition'])) {
                //根据condition进行验证
                $user = $auth->getUserInfo($uid); //获取用户信息,一维数组
                $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
                //dump($command); //debug
                @(eval('$condition=(' . $command . ');'));
                if ($condition) {
                    $authList[] = strtolower($rule['name']);
                }
            } else {
                //只要存在就记录
                $authList[] = strtolower($rule['name']);
            }
        }
        $_authList[$uid . $t] = $authList;

        return array_unique($authList);
    }
    /**
     * 递归显示所有子节点
     * @param array &$children 子节点数组
     */
    public static function showAllChildren(&$children)
    {
        if (!is_array($children)) {
            return;
        }
        
        foreach ($children as &$child) {
            $child['is_show'] = true;
            if (isset($child['children']) && is_array($child['children'])) {
                self::showAllChildren($child['children']);
            }
        }
        
        unset($child);
    }
}